/*+***********************************************************************************
 Filename: \03_mcu_sparrowrvcore_02\src\perips\intctrl.v
 Description: a simple interrupt controller module. 
   max 32 int source signal.

 Modification:
   2024.05.24 Creation   H.Zheng  

Copyright (C) 2024  Zheng Hui (hzheng@gzhu.edu.cn)

License: MulanPSL-2.0

***********************************************************************************-*/
/**
 * I/O Regs:
 *  offset      reg
 * 0x00         effective interrupt request
 * 0x04         interrupt mask (1 means enable)  
 * 0x08         pending interrupt request
 */
module interrupt_controller(

    input wire clk,
    input wire reset_n,

    input wire[31:0] data_i,
    input wire[3:0] addr_i,
    input wire we_i,
    input wire ce_i,

    output wire[31:0] data_o,
    
    input wire [31:0] int_req_sig_i, //int request signal from other peripheral modules
    output wire int_sig_o  //effective ext_int request signal to core

    );

    reg [31:0] int_mask; //interrupt mask

    wire write_en = ce_i & we_i;
    wire read_en = ce_i & (~we_i);

    /**
     * int mask logic
     */
    always @(posedge clk) begin
        if (reset_n == 1'b0) begin
            int_mask <= 32'b0;
        end
        else if (write_en &&(addr_i == 4'h1)) begin
            int_mask <= data_i;
        end
    end

    /**
     * pending interrupt request
     */
    wire [31:0] pending_int_req = int_req_sig_i;
    
    /**
     * effective interrupt request
     */
    wire [31:0] effective_int_req = int_req_sig_i & int_mask;
    

    //output int request
    assign int_sig_o = | effective_int_req;


    /**
     * data return to core
     */
    assign data_o = (addr_i == 4'h0) ? effective_int_req :
                    (addr_i == 4'h1) ? int_mask : 
                    (addr_i == 4'h2) ? pending_int_req : 32'b0;



endmodule
